(function(window) {
    'use strict';

    var rsa = function(params) {
        $.extend(this.params, params);
        this._init();
    };

    rsa.prototype = {
        params: {
            publicKey: '',
        },

        _init: function() {
            var that = this;
            that.getKeyClick();
            that.sendButton();
        },

        /**
         *  获取公钥
         */
        getKeyClick: function() {
            var that = this;
            var param = [];

            $('#getKey').click(function() {
                param.url = 'http://192.168.2.152/test/testrsa.php';
                param.data = {
                    act: 'get'
                };

                ajax(
                    param,
                    function(result) {
                        // 保存公钥
                        that.params.publicKey = result['publicKey'];
                    }
                );
            });
        },

        /**
         *  发送测试数据
         */
        sendButton: function() {
            var that = this;
            var param = []

            $('#sendButton').click(function() {
                var dataText1 = $('#dataText1').val();

                // 加密
                var encrypt = new JSEncrypt();
                encrypt.setPublicKey(that.params.publicKey);
                var encrypted = encrypt.encrypt(dataText1);
                console.log(encrypted);

                param.url = 'http://192.168.2.152/test/testrsa.php';
                param.data = {
                    act: 'data',
                    dataText: encrypted
                };

                ajax(
                    param,
                    function(result) {
                        console.log(result['code']);
                        console.log(result['decrypted']);
                        $('#dataText2').val(result['decrypted']);
                    }
                );
            });
        }
    };
    window.rsa = rsa;
})(window);
